<template>
  <div class="evaluation-criteria">
    <div class="criteria-header">
      <h4>评分标准设置</h4>
      <el-button type="primary" @click="handleAddCriteria">添加评分项</el-button>
    </div>

    <el-table :data="criteriaList" border>
      <el-table-column prop="evaluationName" label="评分项名称" min-width="150" />
      <el-table-column prop="evaluationRemark" label="评分项说明" min-width="200" />
      <el-table-column prop="evaluationWeight" label="权重" width="100">
        <template #default="scope">
          {{ scope.row.evaluationWeight }}%
        </template>
      </el-table-column>
      <el-table-column prop="evaluationScore" label="满分值" width="100" />
      <el-table-column prop="evaluationType" label="评分方式" width="120">
        <template #default="scope">
          <el-tag>{{ getScoreTypeName(scope.row.evaluationType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑评分项对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑评分项' : '添加评分项'"
      width="600px"
    >
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="评分项名称" prop="evaluationName">
          <el-input v-model="form.evaluationName" />
        </el-form-item>
        <el-form-item label="评分项说明" prop="evaluationRemark">
          <el-input
            v-model="form.evaluationRemark"
            type="textarea"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="权重" prop="evaluationWeight">
          <el-input-number
            v-model="form.evaluationWeight"
            :min="0"
            :max="100"
            :step="5"
          />
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item label="满分值" prop="evaluationScore">
          <el-input-number
            v-model="form.evaluationScore"
            :min="0"
            :max="100"
            :step="5"
          />
        </el-form-item>
        <el-form-item label="评分方式" prop="evaluationType">
          <el-select v-model="form.evaluationType">
            <el-option
              v-for="item in scoreTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="评分细则">-->
<!--          <div class="score-rules">-->
<!--            <div -->
<!--              v-for="(rule, index) in form.scoreRules"-->
<!--              :key="index"-->
<!--              class="rule-item"-->
<!--            >-->
<!--              <el-input-number-->
<!--                v-model="rule.score"-->
<!--                :min="0"-->
<!--                :max="form.maxScore"-->
<!--                :step="1"-->
<!--                class="rule-score"-->
<!--              />-->
<!--              <el-input-->
<!--                v-model="rule.description"-->
<!--                placeholder="请输入得分说明"-->
<!--                class="rule-description"-->
<!--              />-->
<!--              <el-button-->
<!--                type="danger"-->
<!--                circle-->
<!--                @click="removeRule(index)"-->
<!--              >-->
<!--                <el-icon><Delete /></el-icon>-->
<!--              </el-button>-->
<!--            </div>-->
<!--            <el-button-->
<!--              type="primary"-->
<!--              plain-->
<!--              @click="addRule"-->
<!--            >-->
<!--              添加评分细则-->
<!--            </el-button>-->
<!--          </div>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import myAxios from '../../../plugins/myAxios'
import { useRouter } from 'vue-router'

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const router = useRouter()

const form = reactive({
  evaluationName: '',
  evaluationRemark: '',
  evaluationWeight: 0,
  evaluationScore: 100,
  evaluationType: 1,
  // scoreRules: []
})

const rules = {
  evaluationName: [
    { required: true, message: '请输入评分项名称', trigger: 'blur' }
  ],
  evaluationRemark: [
    { required: true, message: '请输入评分项说明', trigger: 'blur' }
  ],
  evaluationWeight: [
    { required: true, message: '请设置权重', trigger: 'change' }
  ],
  evaluationType: [
    { required: true, message: '请选择评分方式', trigger: 'change' }
  ]
}

const scoreTypes = [
  { label: '作业评分', value: 1 },
  { label: '课堂评分', value: 2 },
  { label: '综合评分', value: 3 }
]

const criteriaList = ref([])

const getScoreTypeName = (type) => {
  const found = scoreTypes.find(item => item.value === type)
  return found ? found.label : type
}

const handleAddCriteria = () => {
  isEdit.value = false
  form.evaluationName = ''
  form.evaluationRemark = ''
  form.evaluationWeight = 0
  form.evaluationScore = 100
  form.evaluationType = 1
  // form.scoreRules = []
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该评分项吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await myAxios.post(`/admin/evaluation/delete/${row.id}`)
    ElMessage.success('删除成功')
    getCriteriaList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error)
    }
  }
}

const addRule = () => {
  form.scoreRules.push({
    score: 0,
    description: ''
  })
}

const removeRule = (index) => {
  form.scoreRules.splice(index, 1)
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const semester = sessionStorage.getItem('currentSemester')
        const data = {
          ...form,
          semester
        }
        const url = isEdit.value ? '/admin/evaluation/update' : '/admin/evaluation/add'
        await myAxios.post(url, data)
        ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
        dialogVisible.value = false
        getCriteriaList()
      } catch (error) {
        ElMessage.error('保存失败：' + error)
      }
    }
  })
}

const getCriteriaList = async () => {
  try {
    const res = await myAxios.get('/admin/evaluation/list', {
    })
    criteriaList.value = res
  } catch (error) {
    ElMessage.error('获取评分标准失败：' + error)
  }
}

watch(() => router.currentRoute.value.query, (query) => {
  if (query.semester) {
    getCriteriaList()
  }
})

onMounted(() => {
  getCriteriaList()
})
</script>

<style scoped>
.evaluation-criteria {
  margin-top: 20px;
}
.criteria-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.unit {
  margin-left: 10px;
  color: #606266;
}
.score-rules {
  margin-top: 10px;
}
.rule-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
.rule-score {
  width: 120px;
}
.rule-description {
  flex: 1;
}
</style> 